/**
 * Desc :
 * Wiki :
 * User : peimingxiao_dxm
 * Date : 2022/11/30 09:52
 */

package main

import (
	"io"
	"os"
)

func CopyFile(oldFilePath, newFilePath string) error {
	oldOpenFile, err := os.OpenFile(oldFilePath, os.O_RDONLY, 0)
	if err != nil {
		return err
	}
	defer oldOpenFile.Close()
	newOpenFile, err := os.OpenFile(newFilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		return err
	}
	defer newOpenFile.Close()

	tmp := make([]byte, 1024)
	for true {
		n, err := oldOpenFile.Read(tmp)
		if n > 0 {
			write, err := newOpenFile.Write(tmp[:n])
			if err != nil || write == 0 {
				return err
			}
		}
		if err != nil {
			return err
		}
	}
	return nil
}

func CopyFile2(oldFilePath, newFilePath string) error {
	oldOpenFile, err := os.OpenFile(oldFilePath, os.O_RDONLY, 0)
	if err != nil {
		return err
	}
	defer oldOpenFile.Close()
	newOpenFile, err := os.OpenFile(newFilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		return err
	}
	defer newOpenFile.Close()

	_, err = io.Copy(newOpenFile, oldOpenFile)
	return err
}
